﻿CREATE PROCEDURE [maint].[DefragIndex]
@DbName [sysname], @TableName [sysname], @IndexName [sysname], @OutputDiagnostics BIT=0
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @RC int, @ERROR int
	SET @RC = 0

	IF(@OutputDiagnostics = 1)
		BEGIN
			PRINT OBJECT_NAME(@@PROCID)
			PRINT N'	@DbName = N''' + ISNULL(@DbName,N'NULL') + ''''
			PRINT N'	@TableName = N''' + ISNULL(@TableName,N'NULL') + ''''
			PRINT N'	@IndexName = N''' + ISNULL(@IndexName,N'NULL') + ''''
		END

	DECLARE @RebuildStatement nvarchar(255);
	SET @RebuildStatement = 'USE [' + @DbName + '];ALTER INDEX ' + @IndexName + ' ON ' + @TableName + ' REBUILD';

	EXEC @RC = sp_executesql @RebuildStatement;

EXIT_PROC:
	RETURN(@RC)
END